<?php require_once(dirname(__FILE__) . '/../include/config.inc.php');
require_once "function.php";

/*
进度：
0 已经撤单
1 报修成功
2 客服已经联系
3 系统已经派单
4 工程师接单
5 维修完成
6 已经评价
*/
$jindu = empty($jindu) ? '' : htmlspecialchars($jindu); //进度状态
$jindu = intval($jindu);
$uid = $_SESSION['id'];
$userInfo = "";
$this_openid = $_SESSION['openid'];
$manageid = getManageUid($this_openid);

if (isset($uid)) {

    //有session 从数据库中读取用户名信息
    //$openid_str=$_SESSION['openid'];
    $sql = "SELECT u.*,g.groupname  as groupname  FROM `#@__user` as u 
				   left join `#@__usergroup` as g  on u.level=g.id  
				   WHERE u.id='$uid' ";
    $row_u = $dosql->GetOne($sql);
    if (is_array($row_u) && isset($row_u['id'])) {
        // 返回用户 id
        $id = $row['id'];
        $_SESSION['id'] = $id;
        $userInfo = $row_u;
        $level = intval($row_u['level']);
    }
}

if ($level > 5) {
    echo "<script>alert('任务不存在或者已经删除！')</script>";
    exit();
}


$orderid = empty($orderid) ? "" : intval($orderid);
if (isset($orderid)) {

    // 拉取用户信息
    $row = $dosql->GetOne("SELECT o.*, u.school as school,u.province as sheng,u.city as shi , u.city as qu ,u.mobile as mobile, u.truename as truename,u.address as address FROM `#@__order` as o 
							left join  `#@__user`  as u   on o.uid=u.id WHERE o.id='$orderid'");
    if (is_array($row) && isset($row['id'])) {
        // 返回工单数据
        /*
        进度：
        0 已经撤单
        1 报修成功
        2 客服已经联系
        3 系统已经派单
        4 工程师接单
        5 维修完成
        6 已经评价
        */

        $jindu2 = $row['jindu'];
        $apply_type = $row['apply_type'];
        $apply_device = $row['apply_device'];
        $fee = $row['fee'];
        $truename = $row['truename'];
        $school = $row['school'];
        $address = $row['address'];
        $orderidname = date('Ymd', time()) . "-" . $id;

        $typename = getDeviceName($row['apply_type']);


        //故障图片
        $pic_lists = "";
        $previewImage_url = array();
        if ($row['picfiles'] != "") {
            $picurl_arr = json_decode($row['picfiles'], TRUE);
            for ($i = 0; $i < count($picurl_arr); $i++) {
                $previewImage_url[] = $picurl_arr[$i];
                $pic_lists .= '<li class="weui-uploader__file" style="background-image:url(' . $picurl_arr[$i] . ')"><img src="' . $picurl_arr[$i] . '" width="0"/></li>';
            }
        }

    } else {
        echo "<script>alert('任务不存在或者已经删除！')</script>";
        exit();
    }
}
?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>转单-技术支持系统</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="description" content="技术支持系统">
        <link rel="stylesheet" href="lib/weui.min.css">
        <link rel="stylesheet" href="css/jquery-weui.css">
        <link rel="stylesheet" href="css/font-awesome.min.css">
        <link rel="stylesheet" href="css/demos.css">

    </head>
    <style>
        .weui-input { width: 150px; text-align: right; border: solid 1px #fff !important; }

        .m_list label { width: 33%; float: left;}

        .m_list p {margin: 0}

        .content{ width: 100%; height: 90px;}
        .m_list .weui-cell {padding: 10px 0}
    </style>
<body ontouchstart>
    <div class="top">
        <div class="user_top"><i>
                <?php
                if (intval($level) > 1) {
                    echo '<a href="manage.php">' . $userInfo['groupname'] . '</a>';
                } else {
                    echo $userInfo['groupname'];
                } ?>
            </i>
            <div class="user_top_conn"><img src="<?php echo $userInfo['headimgurl'] ?>"/>
                <p><?php echo $userInfo['truename'] ?></p>
                <?php if (intval($level) > 1) { ?>
                    <a class="user_link" href="member.php">返回用户</a>
                <?php } ?>
            </div>
        </div>
    </div>
    <!--工单列表开始-->

    <!--工单详情开始-->
    <div class="main">
        <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i>工单信息</div>
        <div class="weui-form-preview">
            <div class="weui-form-preview__bd">
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">工单号</label>
                    <span class="weui-form-preview__value"><?php echo date("Ymd", $row['post_time']) . "-" . $row['id'] ?></span>
                </div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">单位：</label>
                    <span class="weui-form-preview__value"><?php echo $row['school'] ?></span></div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">报修地址</label>
                    <span class="weui-form-preview__value" id="daohang" data-orderid="<?php echo $row['id'] ?>"><i class="fa fa-map-marker red"></i> <?php echo $row['sheng'] . "-" . $row['shi'] . "-" . $row['qu'] . "-" . $row['address'] ?></span>
                </div>


                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">联系人：</label>
                    <span class="weui-form-preview__value"><a href="tel:<?php echo $row['mobile'] ?>"><i class="fa fa-mobile"></i> <?php echo $row['truename'] . "-" . $row['mobile'] ?></a></span>
                </div>

                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">报修设备</label>
                    <span class="weui-form-preview__value"><i class="fa  fa-print red"></i> <?php echo getDeviceName($row['apply_type']) ?></span>
                </div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">故障描述</label>
                    <span class="weui-form-preview__value"><?php echo $row['content'] ?></span></div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">故障图片</label>
                    <div class="weui-uploader">
                        <div class="weui-uploader__bd">
                            <ul class="weui-uploader__files" id="uploaderFiles">
                                <?php echo $pic_lists; ?>
                            </ul>
                        </div>
                    </div>
                </div>

                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">执行人：</label>
                    <span class="weui-form-preview__value">
        <?php
        if ($row['manageid'] != "") {
            $ids_arr = explode(",", $row['manageid']);
            foreach ($ids_arr as $key => $val) {
                echo ' <i class="fa  fa-user-o red"></i>      ' . getManage($val);
            }


        }
        ?>
        </span></div>

                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label red">维修进度</label>
                    <span class="weui-form-preview__value">
        <ul>
          <?php
          $dosql->Execute("SELECT * FROM `#@__order_log` WHERE orderid='$orderid'  ORDER BY id asc");
          while ($row2 = $dosql->GetArray()) {
              ?>
              <li><i class="fa fa-check-circle"><?php echo $row2['op'] ?></i> <?php echo date("m-d H:i:s", $row2['op_time']) ?></li>
              <?php
          }
          ?>
        </ul>
        </span></div>

            </div>
        </div>
    </div>
    <!--工单详情结束-->
<?php if ($jindu2 < 5 && $jindu2 != 0) { ?>
    <div class="main">
        <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i> 订单变更</div>
        <!--完修模块-->
        <form name="form" id="form" method="post" action="">
            <div class="weui-cells weui-cells_form">
                <div class="weui-cells__title">转单工程师：</div>
                <div class="weui-cells ">
                    <input type="hidden" name="manageids_old" id="manageids_old" value="<?php echo $row['manageid'] ?>">
                    <div class="weui-cells weui-cells_checkbox m_list">

                        <?php
                        $m_ids = $row['manageid'];
                        $ids_arr = explode(",", $row['manageid']);
                        $dosql->Execute("SELECT * FROM `#@__user`   WHERE `level`='3'  ORDER BY id asc");
                        while ($row3 = $dosql->GetArray()) {

                            if (in_array($row3['id'], $ids_arr)) {
                                $chd = ' checked="true"  ';
                            } else {
                                $chd = "";
                            }


                            echo '<label class="weui-cell weui-check__label" for="s'.$row3['id'].'">
                            <div class="weui-cell__hd">
                              <input type="checkbox" ' . $chd . '  class="weui-check" value="'.$row3['id'].'" name="manageid_new" id="s'.$row3['id'].'" >
                              <i class="weui-icon-checked"></i>
                            </div>
                            <div class="weui-cell__bd">
                              <p>' . $row3['truename'] . '</p>
                            </div>
                          </label>';



                        }


                        ?>
                    </div>
                    <div class="weui-cells weui-cells_checkbox m_list">

                        <?php
                        $m_ids = $row['manageid'];
                        $ids_arr = explode(",", $row['manageid']);
                        $dosql->Execute("SELECT * FROM `#@__user`   WHERE `level`='4'  ORDER BY id asc");
                        while ($row3 = $dosql->GetArray()) {

                            if (in_array($row3['id'], $ids_arr)) {
                                $chd = ' checked="true"  ';
                            } else {
                                $chd = "";
                            }


                            echo '<label class="weui-cell weui-check__label" for="s'.$row3['id'].'">
                            <div class="weui-cell__hd">
                              <input type="checkbox" ' . $chd . '  class="weui-check" value="'.$row3['id'].'" name="manageid_new" id="s'.$row3['id'].'" >
                              <i class="weui-icon-checked"></i>
                            </div>
                            <div class="weui-cell__bd">
                              <p>' . $row3['truename'] . '</p>
                            </div>
                          </label>';



                        }


                        ?>
                </div>
                <div class="weui-cells__title">变更原因：</div>
                <div class="weui-cells ">
                    <div class="weui-cell">
                        <div class="weui-cell__bd">
                            <textarea class="form-control content" name="content" id="content" placeholder="请输入文本" rows="3"></textarea>
                            <div class="weui-textarea-counter"><span>0</span>/200</div>
                        </div>
                    </div>
                </div>
            </div>
            <!--上传 开始-->

            <!--上传 结束-->
            <input type="hidden" name="action" id="action" value="add"/>
            <input type="hidden" name="sub_manageids" id="sub_manageids" value="<?php echo $row['manageid'] ?>">
        </form>
        <!-- 完修模块-->
        <div class="sub_btn">
            <a href="javascript:;" class="weui-btn weui-btn_primary" onclick="cfm_order();return false;">确认转单</a></div>
        <div class="clear"></div>
    </div>
<?php } ?>
    <div class="clear"></div>
    <div class="sub_btn"></div>
    <script src="lib/jquery-2.1.4.js"></script>
    <script src="lib/fastclick.js"></script>
    <script src="js/jquery-weui.js"></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script>
        var checkids = [];
        var ids = "<?php echo $row['manageid'] ?>";
        $(function () {
            FastClick.attach(document.body);
            $("input[name='manageid_new']").change(function () {
                // 是否选择工程师
                checkids = [];
                ids = "";
                $("input[name='manageid_new']:checked").each(function (i) {
                    checkids[i] = $(this).val();
                });

                ids = checkids.join(",");
                console.log(ids);
                //重新给隐藏参数赋值
                $("#sub_manageids").val(ids);
                if (checkids.length == 0) {
                    $.toast("请选择工程师", "forbidden");
                    return false;
                }
            });

        });


        //提交表单
        function cfm_order() {
            if ($("#content").val() == "") {
                $.toast("请输入转单详情", "forbidden");
                $("#content").focus();
                return false;
            }

            console.log(ids);
            //判断是否和原有工程师一致
            var manageids_old = $("#manageids_old").val();
            if (ids == manageids_old) {
                $.toast("没有变更工程师", "forbidden");
                return false;

            }

            if ($("#sub_manageids").val() == "") {
                $.toast("至少选择一位工程师", "forbidden");
                return false;
            }

            $("#form").submit();

        }

        wx.config({
            debug: false,
            appId: '<?php echo $signPackage["appId"];?>',
            timestamp: <?php echo $signPackage["timestamp"];?>,
            nonceStr: '<?php echo $signPackage["nonceStr"];?>',
            signature: '<?php echo $signPackage["signature"];?>',
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'openAddress',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage'
            ]
        });
        wx.ready(function () {
            //预览图片
            var apply_images = $("#uploaderFiles_apply").find("img");
            var imgPaths = [];
            apply_images.each(function () {
                imgPaths.push(this.src);
            });
            $("#uploaderFiles_apply").on("click", function () {
                current = imgPaths[0];
                wx.previewImage({
                    current: current,
                    urls: imgPaths
                });
            });


        })


    </script>
<?php
//工单提交处理

if (isset($action) and $action == 'add') {
    if (empty($content)) {
        echo '<script type="text/javascript">
	$.toast("请填写添加转单备注", function() {
		 
		});
	</script>';
        exit();
    }
    $content = htmlspecialchars($content);
    $post_time = time();
    $post_time2 = date("Y-m-d H:i:s", time());


    //修改任务的 执行人
    $dosql->ExecNoneQuery("update  `#@__order` set  manageid='$sub_manageids',jindu='3',qiandao=''  where  id='$orderid' ");
    //插入更新的状态
    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu,manageid,remark,zhuandan,op_manageid) values ('$orderid','转出工单','$post_time','4','$sub_manageids','$content','true','$uid')");

    //插入更新的状态
    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu,manageid,remark,zhuandan,op_manageid) values ('$orderid','工程师被转单','$post_time','3','$sub_manageids','$content','true','$uid')");


    $orderidname = date('Ymd', time()) . "-" . $orderid;


    $ids_arr = explode(",", $sub_manageids);
    //执行人
    $zhixingren = "";
    foreach ($ids_arr as $key => $val) {
        $zhixingren .= getManage($val) . "    ";
    }

    //处理工单
    foreach ($ids_arr as $key => $val) {
        //获取工程师 openid
        $m = $dosql->GetOne("select openid  from `#@__user`  where id='$val'");
        $openid_str = $m['openid'];
        //插入更新的状态


        $orderidname = date('Ymd', time()) . "-" . $orderid;
        //封装为json格式的数据
        $repairname = getRepairMode($apply_device);

        //$repairname = $repairname . "  奖励  " . $fee;


        $send_body['touser'] = $openid_str;
        $send_body['template_id'] = $cfg_neworder;
        $send_body['url'] = $cfg_weburl . 'wx/morderDetail.php?orderid=' . $orderid;
        $send_body['data']['first']['value'] = "📢 您好,您好，您有新的工单信息。执行人变更";
        $send_body['data']['first']['color'] = "#FF0000";
        $send_body['data']['keyword1']['value'] = $orderidname;
        $send_body['data']['keyword1']['color'] = "#173177";
        $send_body['data']['keyword2']['value'] = $repairname;
        $send_body['data']['keyword2']['color'] = "#FF0000";
        $send_body['data']['keyword3']['value'] = $post_time2;
        //$send_body['data']['keyword3']['color'] = "#FF0000";
        $send_body['data']['keyword4']['value'] = "💗" . $school . "-" . $truename;
        $send_body['data']['keyword4']['color'] = "#0e48cb";
        $send_body['data']['keyword5']['value'] = "⛳" . $address;
        $send_body['data']['keyword5']['color'] = "#0e48cb";
        $send_body['data']['remark']['value'] = "👉请点击处理，如有特殊情况，请转单给其他工程师。服务热线:" . $cfg_hotline . "👈";
        $send_body['data']['remark']['color'] = "#66bf45";

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $g_AccessToken;
        $jssdk->https_curl_json($url, $send_body, 'json');
        //$jssdk->return_json_body(['code' => 0, 'msg' => '添加成功']);


    }


    echo '<script type="text/javascript">
        $.toast("转单成功", function() {
             window.location.href="morderDetail.php?orderid=' . $orderid . '";
            });
        </script>';
    exit();

}

?>
<?php require_once('footer.php'); ?>